package com.anxin.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.anxin.service.ExcelService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Slf4j
@Service
public class ExcelServiceImpl implements ExcelService {

    @Value("${file.upload.path}")
    private String uploadPath;

    @Override
    public <T> List<T> importExcel(MultipartFile file, Class<T> clazz) {
        if (file == null || file.isEmpty()) {
            throw new IllegalArgumentException("文件不能为空");
        }

        List<T> dataList = new ArrayList<>();
        try {
            log.info("开始导入Excel文件: {}", file.getOriginalFilename());
            EasyExcel.read(file.getInputStream(), clazz, new ReadListener<T>() {
                @Override
                public void invoke(T data, AnalysisContext context) {
                    dataList.add(data);
                }

                @Override
                public void doAfterAllAnalysed(AnalysisContext context) {
                    log.info("Excel文件解析完成，共导入{}条数据", dataList.size());
                }
            }).sheet().doRead();
        } catch (IOException e) {
            log.error("导入Excel文件失败", e);
            throw new RuntimeException("导入Excel失败: " + e.getMessage());
        }
        return dataList;
    }

    @Override
    public <T> String exportExcel(List<T> data, Class<T> clazz) {
        if (data == null || data.isEmpty()) {
            throw new IllegalArgumentException("导出数据不能为空");
        }

        String fileName = IdUtil.getSnowflakeNextIdStr() + ".xlsx";
        String filePath = uploadPath + File.separator + fileName;

        try {
            log.info("开始导出Excel文件: {}", filePath);
            EasyExcel.write(filePath, clazz)
                    .sheet("Sheet1")
                    .doWrite(data);
            log.info("Excel文件导出成功，共导出{}条数据", data.size());
        } catch (Exception e) {
            log.error("导出Excel文件失败", e);
            throw new RuntimeException("导出Excel失败: " + e.getMessage());
        }

        return fileName;
    }
}
